﻿var jsonData = null;

/**
* applies json data to image object,
*/
function applyDataToImage(data, imageObj, fade) {

    imageObj.attr('src', '/en/ImageFromText/' +
                                data.FontId + '/' +
                                data.Color + '/' +
                                data.Size + '?text=' +
                                data.Text);

    //Align images after loading only for correct width
    imageObj.load(function() {
        if (!fade) {
            imageObj.show();
        }
        var yCord = data.Align.Y - imageObj.height();
        if (data.Align.Halign == 'abs') {
            if (data.Align.GrowTo == 'right') {
                imageObj.css({ left: data.Align.X + "px", top: yCord + "px" });

            }
            else if (data.Align.GrowTo == 'left') {
                var xCord = data.Align.X - imageObj.width();
                imageObj.css({ left: xCord + "px", top: yCord + "px" });
            }
        }
        else if (data.Align.Halign == 'center') {
            var xCord = $("#productImg").width() / 2 - imageObj.width() / 2;
            imageObj.css({ left: xCord + "px", top: yCord + "px" });
        }
        if (fade) {
            imageObj.fadeIn("slow");
        }
    })
        .error(function() { $(this).hide() });
}

function removeCreatedImages() {
    $("#customizationZone img").each(function() {
        if ($(this).attr('id') != 'productImg') {
            $(this).remove();
        }
    });
}

function normalizeTextItem(item, jsData) {
    var widthInPoints = jsData.Width;
    var heightInPoints = jsData.Height;

    item.Align.X = (item.Align.X / widthInPoints) * $("#productImg").width();
    item.Align.Y = (1 - item.Align.Y / heightInPoints) * $("#productImg").height();
    //item.Size = item.Size;// * 1.7;
}


function loadJSONData(templateId) {
    $.getJSON(templJsonPath +"/" + templateId,
            function(data) {
                if (jsonData == null) {
                    jsonData = new Object();
                }
                
                removeCreatedImages();
                $.each(data.Items, function() {
                    var imgId = this.FieldName + 'Img';
                    normalizeTextItem(this,data);
                    
                    if (jsonData[this.FieldName] != null) {
                        this.Text = jsonData[this.FieldName].Text;
                    }
                    $('#' + this.FieldName).val(this.Text);
                    jsonData[this.FieldName] = this;

                    var imgEl = $('<img/>').attr('id', imgId);

                    $('#customizationZone').append(imgEl);
                    imgEl.hide();
                    applyDataToImage(this, imgEl, true);
                });
                //addValidators();
                //$('#field-container').fadeIn('fast');

            });
}


function assignKeyHandlersToFields() {
    $("#contactInfo input").each(function() {
        $(this).keyup(function() {
            var newText = validateField($(this));
            jsonData[$(this).attr('id')].Text = newText;
            var imgSelector = "#" + $(this).attr('id') + "Img";
            applyDataToImage(jsonData[$(this).attr('id')], $(imgSelector), false);

        });
        $(this).keydown(function() {
            validateField($(this));
        });
        $(this).focusout(function() {
        validateField($(this));
        });
        $(this).focus(function() {
        validateField($(this));
        });
        $(this).blur(function() {
        validateField($(this));
        });
        $(this).click(function() {
        validateField($(this));
        });

    });
}
var invalidFields;

function validateField(field) {
    var textVal = $.trim(field.val());
    var maxLength = jsonData[field.attr('id')].MaxLength;
    
    if (textVal.length > maxLength) {
        
        field.addClass("input-validation-error");
        invalidFields[field.attr('id')] = true;
        textVal = textVal.substr(0, maxLength);
    } else {
        field.removeClass("input-validation-error");
        invalidFields[field.attr('id')] = false;
    }
    return textVal;
}

function validateForm() {
    var isValid = true;
    $('#contactInfo input[type="text"]').each(function() {
        validateField($(this));
        if (invalidFields[$(this).attr('id')] != null) {
            isValid = isValid && !invalidFields[$(this).attr('id')];
        }
    });
    return isValid;
}

$(document).ready(function() {

    invalidFields = new Object();
    //$("#productImg").load(function() {

    $('#form0').submit(function() {
        return validateForm();
    });

    assignKeyHandlersToFields();
    $("#layout-list a").each(function() {
        $(this).click(function() {
            var templateId = $(this).attr('id').substr('layout-item-'.length);
            $('#templateId').val(templateId);
            //$('#field-container').fadeOut('fast');
            $('#field-container').load('/Product/InfoDataFieldsControl/' + templateId, function() {
                assignKeyHandlersToFields();
                loadJSONData(templateId);

            });
        });
    });

    //Loads first child of layout as default
    loadJSONData($("#layout-list a:first-child").attr('id').substr('layout-item-'.length));

    //});

});